import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.mysql.jdbc.Connection;
import options.*;
import metadata.DB;
import metadata.cleanup.Title;
import metadata.cleanup.Year;
 
public class MetadataValidator {
	public static void main(String args[]){
		// Configuration file with all the db details
		if(args.length!=1){
			System.err.println("Usage: java PROGRAM <config-file>");
			System.exit(0);
		}
		Options config = new Options(args[0]);
		
		// Get a connection 
		Connection conn = DB.connect(config);
		if(conn!=null){
			System.out.println("Connected!");
		}
	
	   try{
        Statement st = conn.createStatement();
        String q = "select BARCODE,TITLE,CREATOR1,DATE,LANGUAGE,SUBJECT from metadata limit 10000";
        System.out.println("Executing:"+q);
        ResultSet res = st.executeQuery(q);
        while (res.next()) {
          String barcode  = res.getString("BARCODE");
          String title = res.getString("TITLE");
          String author = res.getString("CREATOR1");
          String lang = res.getString("LANGUAGE");
          String subject = res.getString("SUBJECT");
          int year = res.getInt("DATE");
          
          checkAndReport(barcode,title,author,lang,subject,year);
        }
        conn.close();
      }
      catch (SQLException s){
        System.out.println("SQL code does not execute.");
      }    
	}

	private static void checkAndReport(String barcode, String title,
			String author, String lang, String subject, int year) {
		int ERR_COUNT=0;
		
		if(!Title.isValid(title)){
			ERR_COUNT++;
		}
		if(!Year.isValid(year)){
			ERR_COUNT++;
		}
		if(ERR_COUNT>0)
			System.out.println(title+" "+year+" "+ERR_COUNT);
	}
}
